package com.cqs.leetcode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class LongestValidParentheses32 {


    public int longestValidParentheses(String s) {
        int result = 0;
        if (s == null || s.length() <= 1) return result;
        char[] chars = s.toCharArray();
        int i = -1;
        Stack<Integer> stack = new Stack<>();
        //找有效的括号队索引
        while (++i < s.length()) {
            char c = chars[i];
            if (c == '(') {
                stack.push(i);
            } else if (c == ')') {
                //stack为空就是说明有是) 开始的字符case【))())(()】
                //第0个，第1个，第3个）不会入栈 而index=5的右括号不会出栈
                if (!stack.empty()) {
                    Integer left = stack.pop();
                    chars[left] = '1';
                    chars[i] = '1';
                }
            }
        }
        //求最长连续的1窗口
        int cnt = 0;
        for (int j = 0; j < chars.length; j++) {
            if (chars[j] == '1'){
                cnt++;
            }else {
                result = Math.max(cnt,result);
                cnt = 0;
            }
        }
        return Math.max(cnt,result);
    }


    public static void main(String[] args) {
        LongestValidParentheses32 l = new LongestValidParentheses32();
        List<String> testCase = new ArrayList<>();
        testCase.add("()(()");
        testCase.add(")()())()()(");
        testCase.add(")()())");
        testCase.forEach(s->{
            System.out.println(l.longestValidParentheses(s));
        });
    }

}
